from flask import render_template, request, redirect, url_for, session, flash, Blueprint
from models import User, Website, Category, Suggestion, AccessLog, Image
from extensions import db
from utils.download import download_image
from functools import wraps
import re

admin_bp = Blueprint('admin', __name__)


def login_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not session.get('logged_in'):
            return redirect(url_for('admin.login'))
        return f(*args, **kwargs)

    return wrapper


@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['username']).first()
        if user and user.check_password(request.form['password']):
            session['logged_in'] = True
            session['username'] = user.username
            return redirect(url_for('admin.dashboard'))
        flash('用户名或密码错误')
    return render_template('bootstrap5/admin/login.html')


@admin_bp.route('/')
@login_required
def dashboard():
    website_count = Website.query.count()
    category_count = Category.query.count()
    suggestion_count = Suggestion.query.count()
    recent_suggestions = Suggestion.query.order_by(Suggestion.created_at.desc()).limit(5)
    return render_template('bootstrap5/admin/dashboard.html',
                           website_count=website_count,
                           category_count=category_count,
                           suggestion_count=suggestion_count,
                           recent_suggestions=recent_suggestions
                           )


@admin_bp.route('/logout')
def logout():
    session.clear()
    flash('您已登出')
    return redirect(url_for('frontend.index'))


# —— 分类管理 —— #
@admin_bp.route('/categories')
@login_required
def categories():
    cat = Category.query.all()
    return render_template('bootstrap5/admin/categories.html', categories=cat)


@admin_bp.route('/categories', methods=['POST'])
@login_required
def add_category():
    name = request.form.get('name', '').strip()
    description = request.form.get('description', '').strip()
    if name:
        cat = Category(name=name, description=description)
        db.session.add(cat)
        db.session.commit()
        flash('添加成功')
    return redirect(url_for('admin.categories'))


# update_category
@admin_bp.route('/categories/<int:category_id>/update', methods=['POST'])
@login_required
def update_category(category_id):
    cat = Category.query.get_or_404(category_id)
    name = request.form.get('name', '').strip()
    description = request.form.get('description', '').strip()
    if name:
        cat.name = name
        cat.description = description
        db.session.commit()
        flash('更新成功')
    return redirect(url_for('admin.categories'))


@admin_bp.route('/categories/<int:category_id>', methods=['DELETE'])
@login_required
def delete_category(category_id):
    cat = Category.query.get_or_404(category_id)
    for site in cat.websites:
        db.session.delete(site)
    db.session.delete(cat)
    db.session.commit()
    return '', 204


# —— 网站管理 —— #
@admin_bp.route('/websites')
@login_required
def websites():
    sites = Website.query.all()
    cats = Category.query.all()
    return render_template('bootstrap5/admin/websites.html',
                           websites=sites, categories=cats)


@admin_bp.route('/websites', methods=['POST'])
@login_required
def add_website():
    name = request.form.get('name', '').strip()
    url = request.form.get('url', '').strip()
    description = request.form.get('description', '').strip()
    logo = request.form.get('logo', '').strip()
    cat_id = request.form.get('category_id')
    if not (name and url and cat_id):
        flash('名称、网址、分类为必填项')
        return redirect(url_for('admin.websites'))
    if not re.match(r'^https?://', url):
        url = 'http://' + url
    if Website.query.filter_by(url=url).first():
        flash('该网址已存在')
        return redirect(url_for('admin.websites'))
    local_logo = download_image(logo, ip=request.remote_addr)
    site = Website(
        name=name,
        url=url,
        description=description,
        logo=logo,
        local_logo=local_logo,
        category_id=cat_id
    )
    db.session.add(site)
    db.session.commit()
    flash('网站添加成功')
    return redirect(url_for('admin.websites'))


@admin_bp.route('/websites/<int:website_id>', methods=['DELETE'])
@login_required
def delete_website(website_id):
    db.session.delete(Website.query.get_or_404(website_id))
    db.session.commit()
    return '', 204


@admin_bp.route('/websites/<int:website_id>/update', methods=['POST'])
@login_required
def update_website(website_id):
    site = Website.query.get_or_404(website_id)
    name = request.form.get('name', '').strip()
    url = request.form.get('url', '').strip()
    description = request.form.get('description', '').strip()
    logo = request.form.get('logo', '').strip()
    cat_id = request.form.get('category_id')
    if not (name and url and cat_id):
        flash('名称、网址、分类为必填项')
        return redirect(url_for('admin.websites'))
    if not re.match(r'^https?://', url):
        url = 'http://' + url
    exists = Website.query.filter(Website.url == url, Website.id != website_id).first()
    if exists:
        flash('该网址已存在')
        return redirect(url_for('admin.websites'))
    # print(site.local_logo)
    img = Image.query.filter_by(source_url=logo).first()
    if site.local_logo is None or img is None:
        local_logo = download_image(logo, ip=request.remote_addr)
        site.local_logo = local_logo
    site.name = name
    site.url = url
    site.description = description
    site.logo = logo
    site.category_id = cat_id
    db.session.commit()
    flash('网站更新成功')
    return redirect(url_for('admin.websites'))


# —— 建议管理 —— #
@admin_bp.route('/suggestions')
@login_required
def suggestions():
    sug_item = Suggestion.query.order_by(Suggestion.created_at.desc())
    return render_template('bootstrap5/admin/suggestions.html',
                           suggestions=sug_item)


@admin_bp.route('/suggestions/<int:id>/handle', methods=['POST'])
@login_required
def handle_suggestion(id):
    suggestion = Suggestion.query.get_or_404(id)
    first_cat = Category.query.first()
    if not first_cat:
        flash('请先添加分类')
        return redirect(url_for('admin.suggestions'))
    db.session.add(Website(name=suggestion.website, url=suggestion.website, category_id=first_cat.id))
    suggestion.handled = True
    db.session.commit()
    flash('已处理')
    return redirect(url_for('admin.suggestions'))


# —— 用户管理 —— #
@admin_bp.route('/users')
@login_required
def users():
    return render_template('bootstrap5/admin/users.html', users=User.query.all())


@admin_bp.route('/users', methods=['POST'])
@login_required
def users_add():
    username = request.form.get('username', '').strip()
    password = request.form.get('password', '').strip()
    email = request.form.get('email', '').strip()
    if not (username and password and email):
        flash('用户名、密码和邮箱不能为空')
        return redirect(url_for('admin.users'))
    if User.query.filter_by(username=username).first():
        flash('该用户名已存在')
        return redirect(url_for('admin.users'))
    user = User(username=username, email=email)
    user.set_password(password)
    db.session.add(user)
    db.session.commit()
    flash('用户添加成功')
    return redirect(url_for('admin.users'))


@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
@login_required
def delete_user(user_id):
    db.session.delete(User.query.get_or_404(user_id))
    db.session.commit()
    return '', 204


@admin_bp.route('/users/<int:user_id>')
@login_required
def user_detail(user_id):
    user = User.query.get_or_404(user_id)
    return render_template('bootstrap5/admin/user_detail.html', user=user)


@admin_bp.route('/users/<int:user_id>', methods=['POST'])
@login_required
def update_user(user_id):
    user = User.query.get_or_404(user_id)
    user.username = request.form['username']
    user.email = request.form['email']
    user.is_deleted = bool(int(request.form['is_deleted']))
    user.role = request.form['role']
    db.session.commit()
    flash('用户信息已更新')
    return redirect(url_for('admin.user_detail', user_id=user.id))


#  —— 图片管理 —— #
@admin_bp.route('/images')
@login_required
def images():
    from models import Image
    imgs = Image.query.order_by(Image.created_at.desc()).all()
    return render_template('bootstrap5/admin/images.html', images=imgs)


# —— 日志查看 —— #
@admin_bp.route('/logs')
@login_required
def view_logs():
    logs = AccessLog.query.order_by(AccessLog.created_at.desc()).limit(100).all()
    return render_template('bootstrap5/admin/logs.html', logs=logs)
